//
//  UserAccount.swift
//  Swift微博
//
//  Created by 陈竹 on 16/2/26.
//  Copyright © 2016年 陈竹. All rights reserved.
//

import UIKit

private let CZWeiboUserAccountKey="CZWeiboUserAccountKey"
class UserAccount: NSObject {
    /// 用户账户单例
    static let sharedUserAccount = UserAccount()
    var isLogin:Bool{
        return access_token != nil
    }
    //获取授权后的token
    var access_token:String?
    //token过期事件单位是秒数
    var expires_in:NSTimeInterval=0 {
        didSet{
            expiresDate=NSDate(timeIntervalSinceNow: expires_in)
            
        }
        
    }
    //过期时间
    var expiresDate:NSDate?
    //用户id
    var uid:String?
    //用户姓名
    var screen_name:String?
    //用户头像，180X180像素
    var avatar_large:String?
    private override init() {
        super.init()
        loadUserAccount()
    }
    
    
    init(dict:[String:AnyObject] ) {
        super.init()
        //字典转模型
        setValuesForKeysWithDictionary(dict)
    }
    
    //重写这个方法可以去掉多余的属性，不重写会报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //重写这个属性可以模型转字典，把模型直接打印出来
    override var description:String{
        let keys=["access_token","expires_in","uid","screen_name","avatar_large","expiresDate"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
}
// MARK: - 读写用户信息
extension UserAccount{
    ///  使用字典更新模型数据
    ///
    ///  - parameter dict: <#dict description#>
    func updateUserAccount(dict:[String:AnyObject]){
        setValuesForKeysWithDictionary(dict)
        saveUserAccount()
    }
    
    ///  把用户信息写入偏好设置
    private func saveUserAccount(){
        //模型转字典
        let keys=["access_token","uid","screen_name","avatar_large","expiresDate"]
        let dict=dictionaryWithValuesForKeys(keys)
        //存到偏好设置
        NSUserDefaults.standardUserDefaults().setObject(dict, forKey:CZWeiboUserAccountKey)
        print(NSHomeDirectory())
    }
    
    ///  读取用户账户
    func loadUserAccount(){
        
        guard let dict=NSUserDefaults.standardUserDefaults().objectForKey(CZWeiboUserAccountKey) as?[String:AnyObject] else{
            return
        }
        //字典转模型
        setValuesForKeysWithDictionary(dict)
        if isExpired{
            print("token过期")
            access_token=nil
        }else{
            print("token正常")
        }
        
    }
    private var isExpired:Bool{
        //把过期时间和当前时间对比，如果是升序（过期时间比当前时间小），说明已经过期
        return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    
}
